﻿using B.MESUI.Login.A_Public.仪表台;
using B.MESUI.Login.A_Public.仪表台.DTO;
using DevExpress.LookAndFeel;
using DevExpress.XtraCharts;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace B.MESUI.Login.A_Public
{
    public partial class DashboardForm : DevExpress.XtraEditors.XtraForm
    {
      //  工单分页
        private int _currentPage = 1;
        private int _pageSize = 5;
        private int _totalCount = 0;
        private GridControl _workOrderGrid;
        private GridView _workOrderView;
        private BindingSource _workOrderBindingSource = new BindingSource();
        private PanelControl _paginationPanel;


        //用户分页
        private int _customerCurrentPage = 1;
        private int _customerPageSize = 5;
        private int _customerTotalCount = 0;
        private GridControl _customerGrid;
        private GridView _customerView;
        private BindingSource _customerBindingSource = new BindingSource();
        private PanelControl _customerPaginationPanel;

        // 添加 DashboardService 实例
        private readonly DashboardService _dashboardService;

        public DashboardForm()
        {
            InitializeComponent();
            UserLookAndFeel.Default.SetSkinStyle("Office 2019 Colorful");

            // 1. 添加背景
            //AddBackgroundGradient();

            // 2. 绑定 Load 事件
            this.Load += DashboardForm_Load;
            ConfigureHorizontalBarChart(chartProcessRank);
          

            // 3. 初始化仪表台
            InitDashboard();
            // 这里加上初始化
            _dashboardService = new DashboardService();

        }

        public DashboardForm(DashboardService dashboardService)
        {
            _dashboardService = dashboardService;
        }

        // 声明字段保存图表引用
        private ChartControl chartProcessRank;
        private async void DashboardForm_Load(object sender, EventArgs e)
        {
            ConfigureHorizontalBarChart(chartProcessRank);
            await LoadDashboardDataAsync(); // 统计卡片
            await LoadWorkOrderDataAsync(); // 工单表格
            await LoadCustomerDataAsync();//客户表格
            await LoadWorkOrderMonthChartAsync(); // 加载工单数量柱状图
        }

        private async Task LoadDashboardDataAsync()
        {
            try
            {
                // 异步获取各项统计数据
                var productionTotal = await _dashboardService.GetProductionTotalAsync();
                var warehouseTotal =await _dashboardService.GetWarehouseTotalAsync();
                var customerTotal = await _dashboardService.GetCustomerTotalAsync();
                var ioRecordTotal =await _dashboardService.GetIORecordTotalAsync(); 
                

                // 更新统计面板数据
                UpdateStatPanels(productionTotal, customerTotal, ioRecordTotal, warehouseTotal);
            }
            catch (Exception ex)
            {
                // 错误处理
                XtraMessageBox.Show($"加载仪表台数据失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
               private void UpdateStatPanels(int productionTotal, int customerTotal, int ioRecordTotal, int warehouseTotal)
        {
            // 查找并更新统计面板
            foreach (Control control in this.Controls)
            {
                if (control is PanelControl panelTop)
                {
                    foreach (Control flowControl in panelTop.Controls)
                    {
                        if (flowControl is FlowLayoutPanel flowLayout)
                        {
                            // 更新统计面板数据
                            UpdateStatPanelInFlowLayout(flowLayout, productionTotal, customerTotal, ioRecordTotal, warehouseTotal);
                            break;
                        }
                    }
                    break;
                }
            }
        }
          private void UpdateStatPanelInFlowLayout(FlowLayoutPanel flowLayout, int productionTotal, int customerTotal, int ioRecordTotal, int warehouseTotal)
        {
            int panelIndex = 0;
            foreach (Control control in flowLayout.Controls)
            {
                if (control is PanelControl panel)
                {
                    // 根据面板索引更新对应的数据
                    switch (panelIndex)
                    {
                        case 0: // 生产总量
                            UpdatePanelValue(panel, productionTotal.ToString("N0"));
                            break;
                        case 1: // 出入库记录数
                            UpdatePanelValue(panel, ioRecordTotal.ToString("N0"));
                            break;
                        case 2: // 仓库总数
                            UpdatePanelValue(panel, warehouseTotal.ToString("N0"));
                            break;
                        case 3: // 客户数
                            UpdatePanelValue(panel, customerTotal.ToString("N0"));
                            break;
                    }
                    panelIndex++;
                }
            }
        }
       private void UpdatePanelValue(PanelControl panel, string value)
        {
            foreach (Control control in panel.Controls)
            {
                if (control is LabelControl label && label.Name == "labelValue")
                {
                    label.Text = value;
                    break;
                }
            }
        }

        private void ConfigureHorizontalBarChart(ChartControl chart)
        {
            if (chart == null || chart.Diagram == null)
                return;

            if (chart.Diagram is XYDiagram diagram)
            {
                diagram.Rotated = true;
                if (chart.Series.Count > 0)
                {
                    var series = chart.Series[0];
                    ((BarSeriesView)series.View).BarWidth = 0.5;
                }
            }
        }
        private ChartControl chartWorkOrder;
        private void InitDashboard()
        {
            // 1. 顶部统计卡片 - 使用 FlowLayoutPanel 更灵活布局
            var panelTop = new PanelControl
            {
                Dock = DockStyle.Top,
                Height = 120,
                BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder
            };

            var flowLayout = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                AutoSize = true,
                WrapContents = true,
                Padding = new Padding(30),
                FlowDirection = FlowDirection.LeftToRight,
            };

           
         // 使用占位符，数据将在异步加载后更新
            flowLayout.Controls.Add(CreateStatPanel("生产工单总量", "加载中...", "⚙️"));
            flowLayout.Controls.Add(CreateStatPanel("出入库记录数", "加载中...", "⚠️"));
            flowLayout.Controls.Add(CreateStatPanel("仓库总数", "加载中...", ""));
            flowLayout.Controls.Add(CreateStatPanel("客户订单数", "加载中...", "🚚"));
            panelTop.Controls.Add(flowLayout);
            this.Controls.Add(panelTop);

            // 2. 主体布局
            var mainPanel = new PanelControl { Dock = DockStyle.Fill, BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder };
            var mainLayout = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 3 };
            mainLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 60));
            mainLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 40));
            // mainLayout初始化后，立刻加上这段
            mainLayout.RowStyles.Clear();
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 60));
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 35));
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 50)); // 分页控件固定高度
            mainPanel.Controls.Add(mainLayout);
            this.Controls.Add(mainPanel);
            // 3. 工单数量柱状图
             chartWorkOrder = CreateBarChart("工单数量", new string[0], new int[0]);
            mainLayout.Controls.Add(chartWorkOrder, 0, 0);


            // 4. 工序环节排行条形图
            var chartProcessRank = CreateHorizontalBarChart("工序环节排行", new[] { "4序", "6序", "7序", "8序", "9序", "10序", "11序", "12序", "13序", "14序" }, new[] { 40, 36, 35, 33, 32, 30, 28, 27, 25, 20 });
            mainLayout.Controls.Add(chartProcessRank, 1, 0);

            // 5. 工单进度表格
            var gridWorkOrder = CreateWorkOrderGrid();
            mainLayout.Controls.Add(gridWorkOrder, 0, 1);

            // 5.1 分页控件
            var paginationPanel = CreatePaginationPanel();
            mainLayout.Controls.Add(paginationPanel, 0, 2);
            mainLayout.SetColumnSpan(paginationPanel, 2); // 让分页控件横跨两列

            // 6. 出货订单表格
            var gridOrder = CreateOrderGrid();
            _customerGrid = CreateCustomerGrid();
            mainLayout.Controls.Add(_customerGrid, 1, 1);

            _customerPaginationPanel = CreateCustomerPaginationPanel();
            mainLayout.Controls.Add(_customerPaginationPanel, 1, 2);

            // 7. 底部生产WIP柱状图
            var chartWip = CreateWipChart();
            chartWip.Dock = DockStyle.Bottom;
            chartWip.Height = 200;
            this.Controls.Add(chartWip);

            this.Controls.Add(mainPanel);
        }
        //客户信息分页表
        private GridControl CreateCustomerGrid()
        {
            _customerGrid = new GridControl { Dock = DockStyle.Fill };
            _customerView = new GridView(_customerGrid);
            _customerGrid.MainView = _customerView;
            _customerGrid.DataSource = _customerBindingSource;

            _customerView.Columns.AddVisible("customeR_NAME", "客户名称");
            _customerView.Columns.AddVisible("customeR_NODE", "客户编码");
            _customerView.Columns.AddVisible("crediT_CODE", "信用编码");

            _customerView.OptionsView.ShowGroupPanel = false;
            _customerView.OptionsBehavior.Editable = false;
            _customerView.RowHeight = 30;

            return _customerGrid;
        }
        //客户分页刷新方法
        private void UpdateCustomerPagination()
        {
            _customerPaginationPanel.Controls.Clear();
            int totalPages = (_customerTotalCount + _customerPageSize - 1) / _customerPageSize;

            var lbl = new LabelControl
            {
                Text = $"第 {_customerCurrentPage} / {totalPages} 页  共 {_customerTotalCount} 条",
                Location = new Point(10, 10),
                AutoSize = true
            };
            _customerPaginationPanel.Controls.Add(lbl);

            var btnPrev = new SimpleButton { Text = "上一页", Location = new Point(150, 5), Enabled = _customerCurrentPage > 1 };
            var btnNext = new SimpleButton { Text = "下一页", Location = new Point(220, 5), Enabled = _customerCurrentPage < totalPages };

            btnPrev.Click += async (s, e) => { _customerCurrentPage--; await LoadCustomerDataAsync(); };
            btnNext.Click += async (s, e) => { _customerCurrentPage++; await LoadCustomerDataAsync(); };

            _customerPaginationPanel.Controls.Add(btnPrev);
            _customerPaginationPanel.Controls.Add(btnNext);
        }
        //客户数据加载方法
        private async Task LoadCustomerDataAsync()
        {
            var (list, totalCount) = await _dashboardService.GetCustomerListAsync(_customerCurrentPage, _customerPageSize);
            _customerTotalCount = totalCount;
            _customerBindingSource.DataSource = list;
            UpdateCustomerPagination();
        }
        //工单柱状图
        private async Task LoadWorkOrderMonthChartAsync()
        {
            var stats = await _dashboardService.GetWorkOrderMonthStatsAsync();
            if (chartWorkOrder.InvokeRequired)
            {
                chartWorkOrder.Invoke(new Action(() => UpdateWorkOrderChart(stats)));
            }
            else
            {
                UpdateWorkOrderChart(stats);
            }
        }
   

        private void UpdateWorkOrderChart(List<WorkOrderMonthStatDto> stats)
        {
            chartWorkOrder.Series.Clear();
            var series = new Series("工单数量", ViewType.Bar);

            foreach (var item in stats)
            {
                string label = item.starT_TIME.ToString("yyyy年MM月");
                series.Points.Add(new SeriesPoint(label, item.totalNUMBER_COL));
            }

            chartWorkOrder.Series.Add(series);
            ((BarSeriesView)series.View).BarWidth = 0.5;
            chartWorkOrder.Legend.Visibility = DevExpress.Utils.DefaultBoolean.False;
        }
        private PanelControl CreateCustomerPaginationPanel()
        {
            _customerPaginationPanel = new PanelControl
            {
                Height = 40,
                Dock = DockStyle.Fill,
                BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder
            };
            return _customerPaginationPanel;
        }
        private PanelControl CreateStatPanel(string title, string value, string icon = null)
        {
            var panel = new PanelControl
            {
                Width = 180,
                Height = 80,
                BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.Simple,
            };

            var labelTitle = new LabelControl
            {
                Text = title,
                Font = new Font("微软雅黑", 10, FontStyle.Regular),
                ForeColor = Color.FromArgb(64, 64, 64),
                Location = new Point(10, 10),
                AutoSize = true
            };

            var labelValue = new LabelControl
            {
                Name = "labelValue", // 关键：加上Name
                Text = value,
                Font = new Font("微软雅黑", 20, FontStyle.Bold),
                ForeColor = Color.FromArgb(30, 144, 255),
                Location = new Point(10, 35),
                AutoSize = true
            };

            if (!string.IsNullOrEmpty(icon))
            {
                var labelIcon = new LabelControl
                {
                    Text = icon,
                    Font = new Font("Segoe UI Emoji", 20),
                    Location = new Point(140, 10)
                };
                panel.Controls.Add(labelIcon);
            }

            panel.Controls.Add(labelTitle);
            panel.Controls.Add(labelValue);

            return panel;
        }
        private ChartControl CreateBarChart(string title, string[] xLabels, int[] values)
        {
            var chart = new ChartControl { Dock = DockStyle.Fill };
            var series = new Series(title, ViewType.Bar);

            for (int i = 0; i < xLabels.Length; i++)
                series.Points.Add(new SeriesPoint(xLabels[i], values[i]));

            chart.Series.Add(series);

            // ✅ 设置柱子宽度（1.0 表示占满空间，0.5 表示一半）
            ((BarSeriesView)series.View).BarWidth = 8;

            chart.Legend.Visibility = DevExpress.Utils.DefaultBoolean.False;

            return chart;
        }
        private ChartControl CreateHorizontalBarChart(string title, string[] yLabels, int[] values)
        {
            var chart = new ChartControl { Dock = DockStyle.Fill };
            var series = new Series(title, ViewType.Bar);

            for (int i = 0; i < yLabels.Length; i++)
                series.Points.Add(new SeriesPoint(yLabels[i], values[i]));

            chart.Series.Add(series);
            chart.Legend.Visibility = DevExpress.Utils.DefaultBoolean.False;

            // 保存图表引用供后续使用
            chartProcessRank = chart;

            return chart;
        }
        private GridControl CreateWorkOrderGrid()
        {
            _workOrderGrid = new GridControl { Dock = DockStyle.Fill };
            _workOrderView = new GridView(_workOrderGrid);
            _workOrderGrid.MainView = _workOrderView;
            _workOrderGrid.DataSource = _workOrderBindingSource;

            // 设置列
            _workOrderView.Columns.AddVisible("CodeId", "工单号");
            _workOrderView.Columns.AddVisible("WorkOrderType", "类型");
            _workOrderView.Columns.AddVisible("ProcessProgress", "进度");
            _workOrderView.Columns.AddVisible("NumberCol", "总数");

            _workOrderView.OptionsView.ShowGroupPanel = false;
            _workOrderView.OptionsBehavior.Editable = false;
            _workOrderView.RowHeight = 30;

            return _workOrderGrid;
        }
        private PanelControl CreatePaginationPanel()
        {
            _paginationPanel = new PanelControl
            {
                Height = 40,
                Dock = DockStyle.Fill, // 这里必须是 Fill
                BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder
            };
            return _paginationPanel;
        }

        //工单分页
        private void UpdatePagination()
        {
            _paginationPanel.Controls.Clear();
            int totalPages = (_totalCount + _pageSize - 1) / _pageSize;

            var lbl = new LabelControl
            {
                Text = $"第 {_currentPage} / {totalPages} 页  共 {_totalCount} 条",
                Location = new Point(10, 10),
                AutoSize = true
            };
            _paginationPanel.Controls.Add(lbl);

            var btnPrev = new SimpleButton { Text = "上一页", Location = new Point(150, 5), Enabled = _currentPage > 1 };
            var btnNext = new SimpleButton { Text = "下一页", Location = new Point(220, 5), Enabled = _currentPage < totalPages };

            btnPrev.Click += async (s, e) => { _currentPage--; await LoadWorkOrderDataAsync(); };
            btnNext.Click += async (s, e) => { _currentPage++; await LoadWorkOrderDataAsync(); };

            _paginationPanel.Controls.Add(btnPrev);
            _paginationPanel.Controls.Add(btnNext);
        }
        /// <summary>
        /// 加载数据工单列表数据
        /// </summary>
        /// <returns></returns>
        private async Task LoadWorkOrderDataAsync()
        {
            var (list, totalCount) = await _dashboardService.GetWorkOrdersAsync(_currentPage, _pageSize);
            _totalCount = totalCount;
            _workOrderBindingSource.DataSource = list;
            UpdatePagination();
        }

       
        private GridControl CreateOrderGrid()
        {
            var grid = new GridControl { Dock = DockStyle.Fill };
            var view = new GridView(grid);
            grid.MainView = view;
            DataTable dt = new DataTable();
            dt.Columns.Add("客户");
            dt.Columns.Add("比率");
            dt.Columns.Add("订单量");
            dt.Rows.Add("松下电器(中国)有限公司", "↑ 72%", 842);
            dt.Rows.Add("苹果精密科技有限公司", "↓ 58%", 2321);
            dt.Rows.Add("华为技术有限公司", "↑ 63%", 3553);
            dt.Rows.Add("小米科技有限责任公司", "↑ 32%", 830);
            dt.Rows.Add("广州市美的制冷设备有限公司", "↓ 57%", 5172);
            grid.DataSource = dt;
            view.Appearance.Row.Font = new Font("微软雅黑", 9);
            view.Appearance.HeaderPanel.Font = new Font("微软雅黑", 9, FontStyle.Bold);
            view.Appearance.Row.BackColor = Color.White;
            view.Appearance.Row.BorderColor = Color.LightGray;
            view.Appearance.Row.Options.UseBackColor = true;
            view.Appearance.Row.Options.UseBorderColor = true;

            view.OptionsView.ShowGroupPanel = false;
            view.OptionsBehavior.Editable = false;
            view.RowHeight = 30;
            return grid;
        }
        private ChartControl CreateWipChart()
        {
            var chart = new ChartControl();
            var series1 = new Series("工单", ViewType.Bar);
            var series2 = new Series("元件", ViewType.Bar);
            string[] xLabels = { "1-2025", "2-2025", "3-2025", "4-2025","5-2025", "6-2025", "7-2025" };
            int[] values1 = { 300, 400, 380, 500, 600, 420, 300, 480 };
            int[] values2 = { 500, 600, 420, 300, 480, 520, 410, 390 };
            for (int i = 0; i < xLabels.Length; i++)
            {
                series1.Points.Add(new SeriesPoint(xLabels[i], values1[i]));
                series2.Points.Add(new SeriesPoint(xLabels[i], values2[i]));
            }
            chart.Series.AddRange(new Series[] { series1, series2 });
            chart.Legend.Visibility = DevExpress.Utils.DefaultBoolean.True;
            return chart;
        }
        private void AddBackgroundGradient()
        {
            var backgroundPanel = new Panel { Dock = DockStyle.Fill };
            backgroundPanel.Paint += (s, e) =>
            {
                using (var brush = new LinearGradientBrush(
                    backgroundPanel.ClientRectangle,
                    Color.FromArgb(240, 245, 255),
                    Color.FromArgb(210, 225, 250),
                    LinearGradientMode.Vertical))
                {
                    e.Graphics.FillRectangle(brush, backgroundPanel.ClientRectangle);
                }
            };

            // 添加 Panel 到窗体中
            this.Controls.Add(backgroundPanel);

            // 将它设置为最底层控件（第一个索引）
            this.Controls.SetChildIndex(backgroundPanel, 0);
        }
    }
}